//
//  ZPCommunityViewController.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/11/29.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPCommunityViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "ZPRegisterLoginViewController.h"
#import "ZPRegisterVerificationViewController.h"
#import "ZPBaseNavigationController.h"
#import "ZPConfirmOrderViewController.h"
#import <UShareUI/UMSocialUIManager.h>
#import "SelectCityViewController.h"
#import "ZPBaseTabBarController.h"

@interface ZPCommunityViewController () <UIWebViewDelegate>
{
    UIButton  *cityBtn;
    NSString  *shareText;
    NSMutableArray  *cityArray;
}

@property (weak, nonatomic) IBOutlet UIWebView *mainWebView;

@end

@implementation ZPCommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.title = [NSString  stringWithFormat:@"%@",self.titleStr];
    
    if (self.isPush) {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(navLeftButtonClick)];
    }else {
        [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(selectCityNotification) name:@"selectCityNotification" object:nil];
        
        cityBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [cityBtn.titleLabel  setFont:[UIFont  systemFontOfSize:14.]];
        [cityBtn  setImage:[UIImage  imageNamed:@"Home_Nav_GPS"] forState:UIControlStateNormal];
        [self  refreshCityButtonTitle];
        
        cityArray = [[NSMutableArray  alloc] init];
        [self  requestCityList];
        [self  requestUnReadMsgCount];
        
    }
    [[NSNotificationCenter  defaultCenter] addObserver:self selector:@selector(refreshCellWebView) name:@"refreshCellWebView" object:nil];
    self.mainWebView.delegate = self;
    
    if (self.urlStr) {
        NSURLRequest  *request = [NSURLRequest  requestWithURL:[NSURL  URLWithString:[NSString  stringWithFormat:@"%@",self.urlStr]]];
        [self.mainWebView  loadRequest:request];
    }else {
        [self.navigationController  popViewControllerAnimated:YES];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.isPush) {
        [self.mainWebView  reload];
    }
    
}

- (void)navLeftButtonClick
{
    if ([self.mainWebView  canGoBack]) {
        [self.mainWebView  goBack];
    }else {
        [self.navigationController  popViewControllerAnimated:YES];
    }
}

- (void)cityButtonClick
{
    SelectCityViewController  *viewController = [[SelectCityViewController  alloc] initWithNibName:@"SelectCityViewController" bundle:nil];
    viewController.dataArray = cityArray;
    [self.navigationController  pushViewController:viewController animated:YES];
}

- (void)navRightButtonClick
{
    [UMSocialUIManager setPreDefinePlatforms:@[@(UMSocialPlatformType_WechatSession),@(UMSocialPlatformType_WechatTimeLine)]];
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMSocialPlatformType platformType, NSDictionary *userInfo) {
        if (platformType==UMSocialPlatformType_UserDefine_Begin+2) {
            [UIPasteboard generalPasteboard].string = [NSString stringWithFormat:@"%@",self.mainWebView.request.URL.absoluteString];
            [ZPPromptView showMessage:@"复制成功"];
        }else if (platformType==UMSocialPlatformType_WechatSession){
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString stringWithFormat:@"%@",self.title] descr:[NSString  stringWithFormat:@"%@",shareText] thumImage:[UIImage imageNamed:@"shareIcon"]];
            shareObject.webpageUrl =[NSString stringWithFormat:@"%@",self.mainWebView.request.URL.absoluteString];
            messageObject.shareObject = shareObject;
            
            //调用分享接口
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                if (error) {
                    
                }else{
                    
                }
            }];
        }else if (platformType==UMSocialPlatformType_WechatTimeLine){
            UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
            
            UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:[NSString  stringWithFormat:@"%@",self.title] descr:[NSString  stringWithFormat:@"%@",shareText] thumImage:[UIImage imageNamed:@"shareIcon"]];
            shareObject.webpageUrl =[NSString stringWithFormat:@"%@",self.mainWebView.request.URL.absoluteString];
            messageObject.shareObject = shareObject;
            
            [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
                if (error) {
                    
                }else{
                    
                }
            }];
        }else{
            
        }
        
    }];
}
#pragma mark - Notifications
#pragma mark WebView Cookie重写
- (void)refreshCellWebView
{
    [self.mainWebView  reload];
}

#pragma mark 选择城市
- (void)selectCityNotification
{
    [self  refreshCityButtonTitle];
}

- (void)refreshCityButtonTitle
{
    NSString  *cityName = [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"cityName"];
    if (cityName && ![cityName  isEqual:[NSNull  null]]) {
        
    }else {
        cityName = @"";
    }
    [cityBtn  setTitle:[NSString  stringWithFormat:@"%@",cityName] forState:UIControlStateNormal];
    CGFloat labelWidth = [cityBtn.titleLabel.text sizeWithFont:cityBtn.titleLabel.font].width;
    [cityBtn  setTitleEdgeInsets:UIEdgeInsetsMake(0, -18, 0, 18)];
    [cityBtn  setImageEdgeInsets:UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth)];
    [cityBtn  addTarget:self action:@selector(cityButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [cityBtn  sizeToFit];
    UIBarButtonItem  *cityItem = [[UIBarButtonItem  alloc] initWithCustomView:cityBtn];
    
    UIBarButtonItem *spaceItem = [[UIBarButtonItem alloc]
                                  initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                  target:nil action:nil];
    spaceItem.width = -15;
    self.navigationItem.leftBarButtonItems = [NSArray  arrayWithObjects:spaceItem,cityItem, nil];
    
}

#pragma mark - 网络相关
#pragma mark 城市列表
- (void)requestCityList
{
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"] ,@"teacherId", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/getCityList.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"++++++++++%@",responseObject);
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSArray  *city = [responseObject  objectForKey:@"result"];
            if ([city  isKindOfClass:[NSArray  class]] && city.count > 0) {
                [cityArray  removeAllObjects];
                [cityArray  addObjectsFromArray:city];
                
                NSString  *cityId = [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"cityId"];
                if (cityId && ![cityId  isEqual:[NSNull  null]] && ![cityId  isEqual:@""]) {
                    
                }else {
                    NSDictionary  *tempDic = [cityArray  objectAtIndex:0];
                    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
                    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
                    [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"name"]] forKey:@"cityName"];
                    [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"selectId"]] forKey:@"cityId"];
                    [dataDic  writeToFile:homePath atomically:YES];
                    [[ZPAuthStore  sharedZPAuthStore] resetUserInfoDictionary];
                    [[ZPAuthStore  sharedZPAuthStore] setWebViewCookiesWithType:1];
                    
                    [self  refreshCityButtonTitle];
                }
            }
            
        }
        
    } failure:^(NSError * _Nonnull error) {
       
    }];
}

#pragma mark 未读消息数量
- (void)requestUnReadMsgCount
{
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"] ,@"teacherId", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIPPT@"teacher/getNoReadMessageCount.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"++++++++++%@",responseObject);
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSString  *unReadStr = [NSString  stringWithFormat:@"%@",[responseObject  objectForKey:@"result"]];
            NSInteger  unReadInter = [unReadStr  integerValue];
            if (unReadInter > 0 ) {
                ZPBaseTabBarController  *tabbarController = (ZPBaseTabBarController  *)[UIApplication  sharedApplication].keyWindow.rootViewController;
                NSArray *items = tabbarController.tabBar.items;
                RDVTabBarItem *thirdItem = nil;
                if (items.count > 2) {
                    thirdItem = [items  objectAtIndex:2];
                }
                
                if (unReadInter > 99) {
                    thirdItem.badgeValue = @"99+";
                }else {
                    thirdItem.badgeValue = unReadStr;
                }
            }else {
                
            }
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

#pragma mark - h5与原生交互
#pragma mark h5跳登录
- (void)iosEduToLogin
{
    ZPRegisterLoginViewController  *viewController = [[ZPRegisterLoginViewController  alloc] initWithNibName:@"ZPRegisterLoginViewController" bundle:nil];
    ZPBaseNavigationController  *navController = [[ZPBaseNavigationController  alloc] initWithRootViewController:viewController];
    [self presentViewController:navController animated:YES completion:nil];

}

#pragma mark h5跳注册
- (void)iosEduToRegister
{
    ZPRegisterVerificationViewController  *viewController = [[ZPRegisterVerificationViewController  alloc] initWithNibName:@"ZPRegisterVerificationViewController" bundle:nil];
    [self.navigationController  pushViewController:viewController animated:YES];

}

#pragma mark h5跳订单详情
- (void)iosToOrderDetailWithArray:(NSArray  *)array
{
    NSInteger  count = array.count;
    if (count > 0) {
        ZPConfirmOrderViewController  *viewController = [[ZPConfirmOrderViewController  alloc] initWithNibName:@"ZPConfirmOrderViewController" bundle:nil];
        viewController.orderSn = [NSString  stringWithFormat:@"%@",[[array  objectAtIndex:0] toString]];
        [self.navigationController pushViewController:viewController animated:YES];
    }
}

#pragma mark 获取分享内容
- (void)getShareDescriptionWithArray:(NSArray  *)array
{
    NSInteger  count = [array  count];
    if (count > 0) {
        NSString  *textStr = [[array  objectAtIndex:0] toString];
        if (textStr && ![textStr  isEqual:[NSNull  null]] && ![textStr  isEqual:@""]) {
            shareText = [NSString  stringWithFormat:@"%@",textStr];
            self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"分享图标"] style:UIBarButtonItemStylePlain target:self action:@selector(navRightButtonClick)];
        }else {
            self.navigationItem.rightBarButtonItem = nil;
        }
    }else {
        self.navigationItem.rightBarButtonItem = nil;
    }
}

#pragma mark H5跳首页
- (void)iosToAppHome
{
    if (self.isPush) {
        [self.navigationController  popToRootViewControllerAnimated:YES];
    }
    UITabBarController *tabBarController = (UITabBarController *)self.view.window.rootViewController;
    tabBarController.selectedIndex = 0;
    
}

#pragma mark - UIWebView Delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    self.navigationItem.rightBarButtonItem = nil;
    
    if (self.isPush) {
        [self  showHudithString:@"加载中..."];
        return YES;
    }else {
        if ([request.URL.absoluteString  isEqualToString:CommunityH5Url]) {
            [self  showHudithString:@"加载中..."];
            return YES;
        }else {
            ZPCommunityViewController  *viewController = [[ZPCommunityViewController  alloc] initWithNibName:@"ZPCommunityViewController" bundle:nil];
            viewController.urlStr = request.URL.absoluteString;
            viewController.titleStr = @"";
            viewController.isPush = YES;
            [self.navigationController  pushViewController:viewController animated:YES];
            
            return NO;
        }
    }
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    [self  hiddenHud];
    self.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    
    JSContext *context = [self.mainWebView  valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    __weak ZPCommunityViewController *weakSelf = self;
    context[@"iosEduToLogin"] = ^() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf  iosEduToLogin];
            });
        });
        
    };
    
    context[@"iosEduToRegister"] = ^() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf  iosEduToRegister];
            });
        });
        
    };
    
    context[@"iosToOrderDetail"] = ^() {
        NSArray *args = [JSContext currentArguments];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf  iosToOrderDetailWithArray:args];
            });
        });
        
    };
    
    context[@"iosToAppHome"] = ^() {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf  iosToAppHome];
            });
        });
        
    };
    
    context[@"iosToSetShareContent"] = ^() {
        NSArray *args = [JSContext currentArguments];
        [weakSelf  getShareDescriptionWithArray:args];
    };
    
    NSString *jsStr = @"JShare()";
    [context  evaluateScript:jsStr];
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [self  hiddenHud];
}

- (void)dealloc
{
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:@"refreshCellWebView" object:nil];
    [[NSNotificationCenter  defaultCenter] removeObserver:self name:@"selectCityNotification" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
